<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success">
      <el-step title="还车验车"></el-step>
      <el-step title="违约信息"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <br>
    <template v-if="active == 0">
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-descriptions class="margin-top margin-bottom" :column="2" border>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆油量">
            <el-form-item label="" v-if="control == '1'">
              <el-input v-model="form.fuelCapacity" placeholder="请输入油量"
                style="width:220px;margin-right:15px"></el-input>
              <span v-if="fuelType == '1'">%</span>
              <span v-if="fuelType == '0'">升</span>
            </el-form-item>
            <el-form-item label="" v-else>
              <el-slider v-model="form.fuelCapacity" style="width: 72%;display: inline-block;margin: 0 20px" :max="16"
                show-stops></el-slider>
              <div style="display: inline-block;overflow: hidden">{{ form.fuelCapacity }}/16</div>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆公里数">
            <el-form-item label="">
              <el-input v-model="form.vehicleMileage" placeholder="请输入车辆公里数" style="width:220px;margin-right:15px"
                @keyup.native="form.vehicleMileage = oninput(form.vehicleMileage, 4)"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="验车时间">
            <el-form-item>
              <el-date-picker v-model="form.takeAlsoTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"
                style="width:220px;margin-right:15px"></el-date-picker>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" label="车辆随车物品">
            <el-form-item>
              <el-checkbox-group v-model="form.accessoryItems">
                <template v-for="item in dict.type.car_accessories">
                  <el-checkbox :key="item.id" :label="item.label" :value="item.value"></el-checkbox>
                </template>
              </el-checkbox-group>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="费用信息">
            <el-table :data="alsoCarItems" border>
              <el-table-column label="收费项名称">
                <template slot-scope="{ row }">
                  <el-input v-model="row.deductionsFor"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="扣款金额">
                <template slot-scope="{row}">
                  <el-input v-model="row.deductionsAmount" placeholder="请输入金额"
                    @keyup.native="row.deductionsAmount = oninput(row.deductionsAmount, 2)"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="{ row }">
                  <el-button type="danger" icon="el-icon-delete" size="mini"
                    @click="deleteChargingItems(row)"></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-col :span="24" style="text-align: center">
              <el-button icon="el-icon-plus" @click="addChargingItems">添加收费项</el-button>
            </el-col>
          </el-descriptions-item>
          <template v-if="orderEscrowCarInfo.carSource == 6">
            <el-descriptions-item label-class-name="my-descriptions-label" :span="3" label="托管信息">
              <el-descriptions direction="vertical" :column="4" border>
                <el-descriptions-item label="托管单价">
                  <el-input v-model="form.escrowUnitPrice" placeholder="请输入金额"
                    @keyup.native="form.escrowUnitPrice = oninput(form.escrowUnitPrice, 2)"></el-input>
                </el-descriptions-item>
                <el-descriptions-item label="用车天数"><el-input v-model="form.escrowOrderDays" placeholder="请输入天数"
                    @keyup.native="form.escrowOrderDays = oninput(form.escrowOrderDays, 1)"></el-input></el-descriptions-item>
                <el-descriptions-item label="托管费用"><el-input v-model="form.escrowAmount" placeholder="请输入金额"
                    @keyup.native="form.escrowAmount = oninput(form.escrowAmount, 2)"></el-input></el-descriptions-item>
                <el-descriptions-item label="订单信息">{{ orderEscrowCarInfo.startTime }}至{{ orderEscrowCarInfo.endTime }}
                  {{ orderEscrowCarInfo.leaseTerm }}天</el-descriptions-item>
              </el-descriptions>
            </el-descriptions-item>
          </template>

          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="车身照片">
            <ImageUpload isArray v-model="form.bodyImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="仪表盘/油表">
            <ImageUpload isArray v-model="form.panelImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="内饰照片">
            <ImageUpload isArray v-model="form.interiorImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="车辆划痕">
            <ImageUpload isArray v-model="form.scratchImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="验车视频">
            <ImageUpload isArray v-model="form.videoUrls" :isVideo="true" :isShowTip="false" :limit="1">
            </ImageUpload>
          </el-descriptions-item>
          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="客户签名">
            <ImageUpload isArray v-model="form.signImage" :isShowTip="false" :limit="10"></ImageUpload>
          </el-descriptions-item>

          <el-descriptions-item label-class-name="my-descriptions-label" :span="2" label="其他描述">
            <el-form-item>
              <el-input v-model="form.remark" type="textarea" placeholder="请输入其他描述" maxlength="200"
                show-word-limit></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
      <div class="footer " style="position: fixed;bottom: 50px;right: 50px;">
        <el-button @click="handleJiaocheyanchelist()">交车验车单</el-button>
        <el-button style="margin-top: 12px;" @click="active = 1">下一步</el-button>
        <el-button @click="closeDiolog">取消</el-button>
      </div>
    </template>
    <template v-if="active == 1">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            <MmvTitle title="订单信息"></MmvTitle>
          </template>

          <el-descriptions class="margin-top margin-bottom" :column="3" border>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 订单编号</template>
              {{ detail.orderInfo.orderNo }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 订单状态</template>
              <dict-tag :options="dict.type.sys_order_status" :value="detail.orderInfo.orderStatus" />
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 取车类型</template>
              {{ { 1: '到店取还车', 3: '上门送取车', 4: '上门送车', 5: '上门取车', }[Number(detail.orderInfo.rentalType)] }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预约取车时间</template>
              {{ detail.orderInfo.rentalStartTime }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预约还车时间</template>
              {{ detail.orderInfo.rentalEndTime }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预约租期（天）</template>
              {{ detail.orderInfo.leaseDays }}
            </el-descriptions-item>

            <template v-if="detail.orderInfo.orderStatus > 3 && detail.orderInfo.orderStatus < 10">
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际取车时间</template>
                {{ detail.orderInfo.actualStartTime }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际还车时间</template>
                {{ formData.takeAlsoTime }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际租期（天）</template>
                {{ detail.liquidatedDamages.days }}
              </el-descriptions-item>
            </template>

            <el-descriptions-item label-class-name="my-descriptions-label" span="3"
              v-if="detail.orderInfo.rentalType == 3 || detail.orderInfo.rentalType == 4">
              <template slot="label"> 预约取车地址</template>
              {{ detail.orderInfo.takeAddress }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label" span="3"
              v-if="detail.orderInfo.rentalType == 3 || detail.orderInfo.rentalType == 5">
              <template slot="label"> 预约还车地址</template>
              {{ detail.orderInfo.alsoAddress }}
            </el-descriptions-item>

            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预约取车门店</template>
              {{ detail.orderInfo.reserveTakeStoreName }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预约还车门店</template>
              {{ detail.orderInfo.reserveAlsoStoreName }}
            </el-descriptions-item>
            <el-descriptions-item label-class-name="my-descriptions-label">
              <template slot="label"> 预定车型</template>
              {{ detail.orderInfo.modelName }}
            </el-descriptions-item>


            <template v-if="detail.orderInfo.orderStatus > 3 && detail.orderInfo.orderStatus < 10">
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际取车门店</template>
                {{ detail.orderInfo.takeStoreName }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际还车门店</template>
                {{ detail.orderInfo.orderStatus > 4 ? detail.orderInfo.alsoStoreName : "" }}
              </el-descriptions-item>
              <el-descriptions-item label-class-name="my-descriptions-label">
                <template slot="label"> 实际车型</template>
                {{ detail.orderInfo.actualModelName }}
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-collapse-item>
        <!--        <el-collapse-item name="2">-->
        <!--          <template slot="title">-->
        <!--            <MmvTitle title="租金明细"></MmvTitle>-->
        <!--          </template>-->

        <!--          <div class="ant-popover-inner-content">-->
        <!--            <div class="fee-detail-wrapper">-->
        <!--              <div class="day-item" v-for="(item,index) in detail.liquidatedDamages.orderPriceCalendars" :key="index" :style="{backgroundColor:item.isUsed==2?'#ffffff':'#f1f3f4'}">-->
        <!--                <div class="date-weekname">-->
        <!--                  <div>{{ item.sameDay }}</div>-->
        <!--                  <div>{{ item.dateOfWeek|dateOfWeek}}</div>-->
        <!--                </div>-->
        <!--                <div class="word-break" :class="item.isUsed==2?'price-color':''">¥{{item.price-item.discountAmount}}</div>-->
        <!--                <div class="word-break" v-if="item.discountAmount" style="color: red">优惠¥{{item.discountAmount}}</div>-->
        <!--              </div>-->
        <!--              <div  style="border-left: 1px #716855 solid;margin-top: 10px;"></div>-->
        <!--            </div>-->
        <!--          </div>-->

        <!--        </el-collapse-item>-->
        <el-collapse-item name="2">
          <template slot="title">
            <MmvTitle title="客户信息"></MmvTitle>
          </template>
          <MemberDetail :detail="detail.customerInfo"></MemberDetail>
        </el-collapse-item>
        <el-collapse-item name="3">
          <template slot="title">
            <MmvTitle title="违约信息"></MmvTitle>
          </template>
          <div style="font-size: 16px;padding: 0 50px;">
            <!--            <div>1.提前联系门店，如需提前还车，请在还车前2小时联系门店，在门店营业时间范围内办理还车手续，如未提前联系，可能导致无法及时还车-->
            <!--              如在夜间时间段办理还车手续，请在下单前后咨询门店，夜间情况特殊可能无人办理-->
            <!--            </div>-->
            <!--            2.{{ detail.liquidatedDamages.ruleText }}-->
            {{ detail.liquidatedDamages.ruleText }}
          </div>
        </el-collapse-item>
        <el-collapse-item name="4">
          <template slot="title">
            <MmvTitle title="剩余租金明细"></MmvTitle>
          </template>
          <el-row>
            <div class="item-title">
              价格日历
              <el-popover placement="right" trigger="click">
                <div class="ant-popover-inner-content">
                  <div class="fee-detail-wrapper">
                    <div class="day-item" v-for="(item, index) in detail.liquidatedDamages.orderPriceCalendars"
                      :key="index">
                      <div class="date-weekname">
                        <div>{{ item.sameDay }}</div>
                        <div>{{ item.dateOfWeek | dateOfWeek }}</div>
                      </div>
                      <div class="price-color word-break">¥{{ item.price }}</div>
                    </div>
                  </div>
                </div>
                <el-button slot="reference" icon="el-icon-search" type="text">日租金明细</el-button>
              </el-popover>
            </div>
            <el-table :data="rentItems" border>
              <el-table-column label="" align="center" prop="name" width="200px" />
              <el-table-column label="收费项名称" align="center" prop="chargeProjectName" />
              <el-table-column label="单价" align="center" prop="unitPrice" />
              <el-table-column label="收费类型" align="center" prop="chargeItemsType">
                <template slot-scope="{ row }">
                  <dict-tag :options="dict.type.charge_type" :value="row.chargeItemsType" />
                </template>
              </el-table-column>
              <el-table-column label="数目" align="center" prop="number" />
              <el-table-column label="费用" align="center" prop="chargeMoney" />
              <el-table-column label="已使用费用" align="center" prop="usedMoney">
                <template slot-scope="{ row }">
                  {{ row.usedMoney ? row.usedMoney.toFixed(2) : '0' }}
                </template>
              </el-table-column>
            </el-table>
            <el-form label-width="100px" label-position="right" size="small">
              <el-descriptions :column="1" border
                :labelStyle="{ width: '200px', background: '#fff', color: '#606266', textAlign: 'center' }"
                :contentStyle="{ textAlign: 'center' }">
                <el-descriptions-item label="总费用">{{ totalCost ? totalCost.toFixed(2) : '0' }}</el-descriptions-item>
                <el-descriptions-item label="已使用费用总计">{{ usedRent ? usedRent.toFixed(2) : '0' }}</el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label">
                    提前还车扣款
                    <el-tooltip placement="right-start">
                      <div slot="content" style="font-size: 14px">
                        {{ detail.liquidatedDamages.ruleText }} {{ '(' + detail.liquidatedDamages.formula + ')' }}
                      </div>
                      <el-button type="text"><i class="el-icon-warning-outline"></i></el-button>
                    </el-tooltip>
                  </template>
                  <el-input v-model="deductionRent" @keyup.native="deductionRent = oninput(deductionRent, 2)"
                    style="width: 200px;" class="deductionRent" suffix-icon="el-icon-edit"></el-input>
                </el-descriptions-item>
                <el-descriptions-item label="应收合计">{{ totalAccountsReceivable }}</el-descriptions-item>
                <el-descriptions-item label="已付租金总计">{{ paidRent ? paidRent.toFixed(2) : '0' }}</el-descriptions-item>
                <el-descriptions-item label="应退租金" v-if="rentToBeRefunded > 0">{{ rentToBeRefunded
                  }}</el-descriptions-item>
                <el-descriptions-item label="待付金额总计" v-else>{{ totalAmountToBePaid }}</el-descriptions-item>

              </el-descriptions>
            </el-form>
          </el-row>

          <el-row :gutter="15" v-if="showTips">
            <div style="color: red;padding: 0 40px">已使用费用超出已付租金，您可收齐款项后还车</div>
          </el-row>
        </el-collapse-item>
        <!--        <el-collapse-item name="5">-->
        <!--          <template slot="title">-->
        <!--            <MmvTitle title="退款信息"></MmvTitle>-->
        <!--          </template>-->
        <!--          <el-form label-width="100px" label-position="right" size="small">-->
        <!--            <el-row :gutter="15">-->
        <!--              <el-col :span="8">-->
        <!--                <el-form-item label="剩余租金">¥{{ detail.liquidatedDamages.rent }}元</el-form-item>-->
        <!--              </el-col>-->
        <!--              <el-col :span="8">-->
        <!--                <el-form-item label="违约金额">-->
        <!--                  <el-input v-model="deductionRent" @keyup.native="deductionRent = oninput(deductionRent, 2)"></el-input>-->
        <!--                </el-form-item>-->
        <!--              </el-col>-->
        <!--              <el-col :span="8">-->
        <!--                <el-form-item label="应退租金" style="font-size: 16px;">¥{{ rentToBeRefunded }}元</el-form-item>-->
        <!--              </el-col>-->
        <!--            </el-row>-->
        <!--          </el-form>-->

        <!--        </el-collapse-item>-->
      </el-collapse>

      <div class="footer " style="position: fixed;bottom: 50px;right: 50px;">
        <el-button type="primary" :loading="submitBtnLoading" @click="submitData">确定</el-button>
        <el-button style="margin-top: 12px;" @click="active = 0">上一步</el-button>
        <el-button @click="closeDiolog">取消</el-button>
      </div>

    </template>

    <el-drawer title="交车验车单" :visible.sync="showjiaocheyanchelist" direction="rtl" size="30%">
      <MmvDeliveryList ref="MmvDeliveryList" v-if="showjiaocheyanchelist" :orderNo="orderNo" :type="1">
      </MmvDeliveryList>
    </el-drawer>

  </div>
</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue';
import * as orderApi from "@/api/order";
import Template from "@/views/system/template";
import MmvDeliveryList from "@/views/order/orderBasic/delivery-detail";
import CustomContent from "@/components/custom/content";
import MemberDetail from "@/views/components/memberDetail";
import { delApplication } from "@/api/bills/application";
import { orderEscrowCarDetail } from "@/api/bills/escrow";
import { carOilQuantityt } from '@/api/car/car_basic'

export default {
  components: {
    Template,
    MmvTitle,
    MmvDeliveryList,
    MemberDetail
  },
  dicts: ['sys_pay_type', 'order_payStatus', 'charge_type', 'refund_type', 'sys_order_status', 'car_accessories'],
  // props: ['orderNo'],
  data() {
    return {
      control: null, // 是否是车钥匙
      fuelType: null, // 油量单位  0-升 1-%
      carId: null,
      orderNo: null,
      active: 0,
      nowId: null,
      activeNames: ['1', '4'],
      detail: {
        chargingItems: [],
        orderInfo: {},
        customerInfo: {},
        liquidatedDamages: {
          rent: 0
        },
      },
      showjiaocheyanchelist: false,
      deductionRent: 0,
      // deductionDeposit:0,
      loading: true,
      btnLoadIng: false,
      url: "", // 支付凭证
      submitBtnLoading: false,

      btnloadIng: false,
      form: {
        // orderNo: '',//订单编号   必传
        type: 2,//类型(1交车验车,2还车验车)   必传
        fuelCapacity: '',//车辆油量
        vehicleMileage: '',//公里数
        accessoryItems: [],//车辆随车物品(逗号隔开)
        remark: '',//其他描述
        takeAlsoTime: this.parseTime(new Date()),//取还车时间
        lkosten: 0.0,//补充油费(还车验车)
        bodyImage: [], //车身照片
        panelImage: [],//仪表盘
        interiorImage: [], //内饰照片
        scratchImage: [],//车辆划痕
        videoUrls: [],//验车视频
        signImage: [],//客户签名
        escrowUnitPrice: '',//托管单价
        escrowOrderDays: '',//用车天数
        escrowAmount: '',//托管费用
      },
      rules: {
        fuelCapacity: [{
          required: true,
          message: '车辆油量不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '车辆油量数输入不正确',
          trigger: 'blur',
        }],
        vehicleMileage: [{
          required: true,
          message: '公里数不能为空',
          trigger: 'change'
        }, {
          pattern: /^[0-9]+(.[0-9]{1,2})?$/,
          message: '公里数输入不正确',
          trigger: 'blur',
        }],
        takeAlsoTime: [{
          required: true,
          message: '还车时间不能为空',
          trigger: 'change'
        }]
      },
      alsoCarItems: [], // 收费项列表

      rentItems: [],
      paidRent: 0,
      totalCost: 0,
      usedRent: 0,
      showTips: false,
      orderEscrowCarInfo: {},//托管车辆回显信息

    }
  },
  computed: {
    //应收合计
    totalAccountsReceivable() {
      let a = Number(this.deductionRent) + Number(this.usedRent);
      return a.toFixed(2)
    },
    //待付金额总计
    totalAmountToBePaid() {
      let num = Number(this.deductionRent) + Number(this.usedRent) - Number(this.paidRent);
      return (num < 0 ? 0 : num).toFixed(2)
    },
    rentToBeRefunded() {
      var r1, r2, m, n;
      try {
        r1 = this.detail.liquidatedDamages.rent.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = this.deductionRent.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      //last modify by deeka
      //动态控制精度长度
      n = (r1 >= r2) ? r1 : r2;
      let num = (this.detail.liquidatedDamages.rent * m - this.deductionRent * m) / m;
      return (num < 0 ? 0 : num).toFixed(n);
    },
    // depositToBeRefunded() {
    //   return this.detail.liquidatedDamages.deposit-this.deductionDeposit;
    // }
    formData() {
      const formData = {
        orderNo: this.orderNo,//订单编号   必传
        type: 2,//类型(1交车验车,2还车验车)   必传
        fuelCapacity: this.form.fuelCapacity,//车辆油量
        vehicleMileage: this.form.vehicleMileage,//公里数
        accessoryItems: String(this.form.accessoryItems),//车辆随车物品(逗号隔开)
        remark: this.form.remark,//其他描述
        takeAlsoTime: this.form.takeAlsoTime,//取还车时间
        lkosten: this.form.lkosten,//补充油费(还车验车)
        bodyImage: this.form.bodyImage, //车身照片
        panelImage: this.form.panelImage,//仪表盘
        interiorImage: this.form.interiorImage, //内饰照片
        videoUrls: this.form.videoUrls,
        scratchImage: this.form.scratchImage,//车辆划痕

        signImage: this.form.signImage,//客户签名
        escrowUnitPrice: this.form.escrowUnitPrice,//托管单价
        escrowOrderDays: this.form.escrowOrderDays,//用车天数
        escrowAmount: this.form.escrowAmount,//托管费用
      };
      formData.cost = this.alsoCarItems.map(val => {
        return {
          deductionsFor: val.deductionsFor,
          deductionsAmount: val.deductionsAmount,
          deductionsWay: val.deductionsWay,
        };
      });
      return formData;
    },
  },
  filters: {
    dateOfWeek(val) {
      return {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        7: '星期日',
      }[Number(val)] || '';
    },
    memberType(val) {
      return {
        1: '企业',
        2: '个人',
      }[Number(val)] || '';
    },
    memberSource(val) {
      return {
        1: '搜索',
        2: '分享',
        3: '扫码',
        4: '手动录入',
      }[Number(val)] || '';
    },
    imageUrl(url) {
      return process.env.VUE_APP_BASE_IMAGE_URL + url
    },
  },
  watch: {
    'formData.takeAlsoTime': function (val) {
      if (val) {
        this.costDetail();
      }
    },
    'form.escrowUnitPrice': {
      handler(value) {
        if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
          this.form.escrowAmount = Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays)
        }
      },
      // immediate:true,
      deep: true
    },
    'form.escrowOrderDays': {
      handler(value) {
        if (this.form.escrowOrderDays && this.form.escrowUnitPrice) {
          this.form.escrowAmount = Number(this.form.escrowUnitPrice) * Number(this.form.escrowOrderDays)
        }
      },
      // immediate:true,
      deep: true
    },

  },
  mounted() {
    this.orderNo = this.$route.query.orderNo
    this.control = this.$route.query.control
    this.carId = this.$route.query.carId
    this.costDetail();
    this.getalsoCarItems();
    this.getOrderEscrowCarDetail()
    if (this.$route.query.control == '1') {
      this.carOilQuantity()
    }
  },
  methods: {
    // 获取油量
    carOilQuantity() {
      carOilQuantityt({ id: this.carId }).then((res) => {
        if (res.data) {
          this.$set(this.form, 'fuelCapacity', res.data.fuelLevel)
          this.fuelType = res.data.fuelType
          // this.electricity = res.data.batteryLevel
          // this.batteryType = res.daya.batteryType
        }
      })
    },
    // 获取交还扯托管车辆费用信息
    getOrderEscrowCarDetail() {
      orderEscrowCarDetail(this.orderNo).then(res => {
        this.orderEscrowCarInfo = res.data;
        if (this.orderEscrowCarInfo.carSource == 6) {
          this.form.escrowUnitPrice = this.orderEscrowCarInfo.escrowUnitPrice
          this.form.escrowOrderDays = this.orderEscrowCarInfo.escrowOrderDays
          this.form.escrowAmount = this.orderEscrowCarInfo.escrowAmount
        }
      })
    },
    step() {
      if (this.active-- < 0) this.active = 0;
    },
    next() {
      if (this.active++ > 2) this.active = 0;
    },
    getalsoCarItems() {
      orderApi.alsoCarItems().then(response => {
        const data = response.data.filter(val => val.isAvailable == 1);
        this.alsoCarItems = data.map(val => {
          return {
            ...val,
            checked: false,
            deductionsFor: val.chargeItemsName,
            deductionsAmount: '',
            deductionsWay: '2',
          }
        })
      });
    },
    addChargingItems() {
      this.alsoCarItems.push({
        chargeItemsName: '',
        chargeItemsType: 1,
        deductionsAmount: 0,
        checked: false,
        deductionsFor: '',
        deductionsWay: '2',
        index: new Date().getTime(),
      })
    },
    deleteChargingItems(row) {
      const index = this.alsoCarItems.map(f => f.index).indexOf(row.index);
      this.alsoCarItems.splice(index, 1)
    },
    /** 交车验车单 */
    handleJiaocheyanchelist() {
      this.showjiaocheyanchelist = true
    },
    closeDiolog() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    costDetail() {
      orderApi.earlyReturnDetail({ orderNo: this.orderNo, takeAlsoTime: this.form.takeAlsoTime, type: 2 }).then(response => {
        this.detail = response.data || {};
        this.deductionRent = response.data.liquidatedDamages.damages;
        this.rentItems = response.data.rentItems;
        this.paidRent = response.data.paidRent;
        this.usedRent = response.data.usedRent;
        this.totalCost = response.data.oldRent;
        this.showTips = this.paidRent < this.usedRent;
        this.detail.customerInfo.labelClassify = response.data.customerInfo.labelClassify.split(',')
        this.loading = false
      });
    },
    submitData() {
      if (!this.formData.vehicleMileage) {
        this.$message.error("公里数不能为空");
        return;
      }
      if (!this.formData.takeAlsoTime) {
        this.$message.error("还车时间不能为空");
        return;
      }
      if (this.showTips) {
        let that = this
        this.$modal.confirm('已使用费用超出已付租金,是否确认继续操作？').then(function () {
          that.doEarlyReturn();
        })
      } else {
        this.doEarlyReturn();
      }
    },
    doEarlyReturn() {
      let that = this
      that.submitBtnLoading = true
      orderApi.earlyReturn({
        orderNo: that.orderNo,
        deductionRent: that.deductionRent,
        usedRent: that.usedRent,
        rentToBeRefunded: that.rentToBeRefunded,
        rentItems: that.rentItems,
        ruleText: that.detail.liquidatedDamages.ruleText,
        ...that.formData
      }).then(response => {

        that.$message.success(response.msg);
        that.closeDiolog();
      }).finally(err => {
        that.submitBtnLoading = false
      });
    },
    getSummaries(param) {
      const {
        columns,
        data
      } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1) {
          const values = data.map(item => Number(item[column.property]));
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        }
      });

      return sums;
    },

  },

}
</script>

<style scoped>
.fee-detail-wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  max-width: 420px;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -ms-flex-direction: row;
  flex-direction: row;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  max-height: 400px;
  overflow-y: auto;
}

.day-item {
  width: 80px;
  text-align: center;
  margin-top: 10px;
}

.price-color {
  color: #ff8b26;
}

/deep/ .deductionRent .el-input__inner {
  text-align: center;
  font-weight: bold;
}
</style>
